//=============================================================================
// User_Auth.js
// 作者: 豆包编程助手
// 版本: 1.0.0
// 说明: 为RPG Maker MZ添加登录注册功能
// 依赖: API_Data_Loader.js 插件
//=============================================================================

/*:
 * @target MZ
 * @plugindesc 为游戏添加登录注册功能
 * @author 豆包编程助手
 * @url 
 * @help User_Auth.js
 * 
 * 这个插件需要配合API_Data_Loader.js使用，
 * 提供用户登录和注册功能，并通过API与服务器交互。
 * 
 * 插件参数:
 *   登录API端点 - 用户登录的API路径
 *   注册API端点 - 用户注册的API路径
 *   用户信息API端点 - 获取当前用户信息的API路径
 *   自动登录 - 是否启用自动登录功能
 *   登录后场景 - 登录成功后跳转的场景
 * 
 * @param loginEndpoint
 * @text 登录API端点
 * @desc 用户登录的API路径
 * @default auth/login
 * 
 * @param registerEndpoint
 * @text 注册API端点
 * @desc 用户注册的API路径
 * @default auth/register
 * 
 * @param userInfoEndpoint
 * @text 用户信息API端点
 * @desc 获取当前用户信息的API路径
 * @default auth/me
 * 
 * @param autoLogin
 * @text 自动登录
 * @desc 是否启用自动登录功能
 * @default true
 * @type boolean
 * 
 * @param postLoginScene
 * @text 登录后场景
 * @desc 登录成功后跳转的场景
 * @default Scene_Title
 * @type select
 * @option 标题界面
 * @value Scene_Title
 * @option 地图界面
 * @value Scene_Map
 */

(() => {
    const pluginName = "User_Auth";
    const parameters = PluginManager.parameters(pluginName);
    
    // 插件配置
    const AuthConfig = {
        loginEndpoint: parameters.loginEndpoint.trim(),
        registerEndpoint: parameters.registerEndpoint.trim(),
        userInfoEndpoint: parameters.userInfoEndpoint.trim(),
        autoLogin: parameters.autoLogin === "true",
        postLoginScene: parameters.postLoginScene
    };
    
    // 当前登录用户信息
    let currentUser = null;
    
    // 认证相关API
    window.AuthClient = {
        /**
         * 用户登录
         * @param {string} username 用户名
         * @param {string} password 密码
         * @returns {Promise} 登录结果
         */
        login: async function(username, password) {
            const url = `${Config.baseApiUrl}/${AuthConfig.loginEndpoint}`;
            
            try {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ username, password }),
                    credentials: 'include' // 用于处理cookie
                });
                
                const data = await response.json();
                
                if (!response.ok) {
                    throw new Error(data.message || '登录失败');
                }
                
                // 保存登录状态
                currentUser = data.user;
                if (AuthConfig.autoLogin) {
                    localStorage.setItem('lastLogin', username);
                    // 如果服务器返回了token，可以在这里保存
                    if (data.token) {
                        localStorage.setItem('authToken', data.token);
                    }
                }
                
                return data;
            } catch (error) {
                console.error('登录失败:', error);
                throw error;
            }
        },
        
        /**
         * 用户注册
         * @param {string} username 用户名
         * @param {string} password 密码
         * @param {string} email 邮箱(可选)
         * @returns {Promise} 注册结果
         */
        register: async function(username, password, email = '') {
            const url = `${Config.baseApiUrl}/${AuthConfig.registerEndpoint}`;
            
            try {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ username, password, email })
                });
                
                const data = await response.json();
                
                if (!response.ok) {
                    throw new Error(data.message || '注册失败');
                }
                
                return data;
            } catch (error) {
                console.error('注册失败:', error);
                throw error;
            }
        },
        
        /**
         * 获取当前用户信息
         * @returns {Promise} 用户信息
         */
        getUserInfo: async function() {
            if (currentUser) {
                return Promise.resolve(currentUser);
            }
            
            // 尝试从缓存或token获取用户信息
            const token = localStorage.getItem('authToken');
            if (!token) {
                return Promise.reject(new Error('未登录'));
            }
            
            const url = `${Config.baseApiUrl}/${AuthConfig.userInfoEndpoint}`;
            
            try {
                const response = await fetch(url, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                const data = await response.json();
                
                if (!response.ok) {
                    throw new Error(data.message || '获取用户信息失败');
                }
                
                currentUser = data;
                return data;
            } catch (error) {
                console.error('获取用户信息失败:', error);
                // 清除无效的token
                localStorage.removeItem('authToken');
                throw error;
            }
        },
        
        /**
         * 用户登出
         */
        logout: function() {
            currentUser = null;
            localStorage.removeItem('authToken');
            // 可选：调用服务器登出接口
        },
        
        /**
         * 检查用户是否已登录
         * @returns {boolean} 是否登录
         */
        isLoggedIn: function() {
            return !!currentUser || !!localStorage.getItem('authToken');
        },
        
        /**
         * 获取当前登录用户
         * @returns {object|null} 用户信息
         */
        getCurrentUser: function() {
            return currentUser;
        }
    };
    
    // 登录场景
    function Scene_Login() {
        this.initialize(...arguments);
    }
    
    Scene_Login.prototype = Object.create(Scene_MenuBase.prototype);
    Scene_Login.prototype.constructor = Scene_Login;
    
    Scene_Login.prototype.initialize = function() {
        Scene_MenuBase.prototype.initialize.call(this);
    };
    
    Scene_Login.prototype.create = function() {
        Scene_MenuBase.prototype.create.call(this);
        this.createBackground();
        this.createWindowLayer();
        this.createLoginWindow();
        this.createStatusWindow();
        this.createButtons();
    };
    
    Scene_Login.prototype.createBackground = function() {
        this._backgroundSprite = new Sprite();
        this._backgroundSprite.bitmap = SceneManager.backgroundBitmap();
        this.addChild(this._backgroundSprite);
    };
    
    Scene_Login.prototype.createLoginWindow = function() {
        const width = 400;
        const height = 200;
        const x = (Graphics.width - width) / 2;
        const y = (Graphics.height - height) / 2 - 50;
        
        this._usernameWindow = new Window_InputText(x, y, width, 60, '用户名');
        this._passwordWindow = new Window_InputText(x, y + 70, width, 60, '密码', true);
        
        // 尝试填充上次登录的用户名
        if (AuthConfig.autoLogin) {
            const lastUser = localStorage.getItem('lastLogin');
            if (lastUser) {
                this._usernameWindow.setText(lastUser);
            }
        }
        
        this.addWindow(this._usernameWindow);
        this.addWindow(this._passwordWindow);
    };
    
    Scene_Login.prototype.createStatusWindow = function() {
        const width = 400;
        const height = 60;
        const x = (Graphics.width - width) / 2;
        const y = (Graphics.height / 2) + 80;
        
        this._statusWindow = new Window_Base(x, y, width, height);
        this._statusWindow.clear();
        this.addWindow(this._statusWindow);
    };
    
    Scene_Login.prototype.createButtons = function() {
        const buttonWidth = 150;
        const buttonHeight = 50;
        const x = (Graphics.width - buttonWidth * 2 - 20) / 2;
        const y = (Graphics.height / 2) + 150;
        
        // 登录按钮
        this._loginButton = new Sprite_Button();
        this._loginButton.bitmap = new Bitmap(buttonWidth, buttonHeight);
        this._loginButton.bitmap.fontSize = 20;
        this._loginButton.bitmap.drawText('登录', 0, 0, buttonWidth, buttonHeight, 'center');
        this._loginButton.x = x;
        this._loginButton.y = y;
        this._loginButton.setClickHandler(this.doLogin.bind(this));
        this.addChild(this._loginButton);
        
        // 注册按钮
        this._registerButton = new Sprite_Button();
        this._registerButton.bitmap = new Bitmap(buttonWidth, buttonHeight);
        this._registerButton.bitmap.fontSize = 20;
        this._registerButton.bitmap.drawText('注册', 0, 0, buttonWidth, buttonHeight, 'center');
        this._registerButton.x = x + buttonWidth + 20;
        this._registerButton.y = y;
        this._registerButton.setClickHandler(this.goToRegister.bind(this));
        this.addChild(this._registerButton);
        
        // 返回按钮
        this._backButton = new Sprite_Button();
        this._backButton.bitmap = new Bitmap(100, 40);
        this._backButton.bitmap.fontSize = 16;
        this._backButton.bitmap.drawText('返回', 0, 0, 100, 40, 'center');
        this._backButton.x = 20;
        this._backButton.y = 20;
        this._backButton.setClickHandler(this.popScene.bind(this));
        this.addChild(this._backButton);
    };
    
    Scene_Login.prototype.doLogin = async function() {
        const username = this._usernameWindow.text().trim();
        const password = this._passwordWindow.text().trim();
        
        if (!username || !password) {
            this.showStatus('请输入用户名和密码', '#ff0000');
            return;
        }
        
        this.showStatus('正在登录...', '#0000ff');
        
        try {
            await AuthClient.login(username, password);
            this.showStatus('登录成功！正在进入游戏...', '#00ff00');
            
            // 延迟一段时间后跳转
            setTimeout(() => {
                const sceneClass = window[AuthConfig.postLoginScene];
                if (sceneClass) {
                    SceneManager.goto(sceneClass);
                } else {
                    SceneManager.goto(Scene_Title);
                }
            }, 1000);
        } catch (error) {
            this.showStatus(error.message || '登录失败', '#ff0000');
        }
    };
    
    Scene_Login.prototype.goToRegister = function() {
        SceneManager.push(Scene_Register);
    };
    
    Scene_Login.prototype.showStatus = function(text, color = '#000000') {
        this._statusWindow.clear();
        this._statusWindow.changeTextColor(color);
        this._statusWindow.drawText(text, 0, 0, this._statusWindow.width, this._statusWindow.lineHeight(), 'center');
    };
    
    // 注册场景
    function Scene_Register() {
        this.initialize(...arguments);
    }
    
    Scene_Register.prototype = Object.create(Scene_MenuBase.prototype);
    Scene_Register.prototype.constructor = Scene_Register;
    
    Scene_Register.prototype.initialize = function() {
        Scene_MenuBase.prototype.initialize.call(this);
    };
    
    Scene_Register.prototype.create = function() {
        Scene_MenuBase.prototype.create.call(this);
        this.createBackground();
        this.createWindowLayer();
        this.createRegisterWindows();
        this.createStatusWindow();
        this.createButtons();
    };
    
    Scene_Register.prototype.createBackground = function() {
        this._backgroundSprite = new Sprite();
        this._backgroundSprite.bitmap = SceneManager.backgroundBitmap();
        this.addChild(this._backgroundSprite);
    };
    
    Scene_Register.prototype.createRegisterWindows = function() {
        const width = 400;
        const height = 60;
        const x = (Graphics.width - width) / 2;
        const startY = (Graphics.height / 2) - 150;
        
        this._usernameWindow = new Window_InputText(x, startY, width, height, '用户名');
        this._passwordWindow = new Window_InputText(x, startY + 70, width, height, '密码', true);
        this._confirmWindow = new Window_InputText(x, startY + 140, width, height, '确认密码', true);
        this._emailWindow = new Window_InputText(x, startY + 210, width, height, '邮箱(可选)');
        
        this.addWindow(this._usernameWindow);
        this.addWindow(this._passwordWindow);
        this.addWindow(this._confirmWindow);
        this.addWindow(this._emailWindow);
    };
    
    Scene_Register.prototype.createStatusWindow = function() {
        const width = 400;
        const height = 60;
        const x = (Graphics.width - width) / 2;
        const y = (Graphics.height / 2) + 150;
        
        this._statusWindow = new Window_Base(x, y, width, height);
        this._statusWindow.clear();
        this.addWindow(this._statusWindow);
    };
    
    Scene_Register.prototype.createButtons = function() {
        const buttonWidth = 150;
        const buttonHeight = 50;
        const x = (Graphics.width - buttonWidth * 2 - 20) / 2;
        const y = (Graphics.height / 2) + 220;
        
        // 注册按钮
        this._registerButton = new Sprite_Button();
        this._registerButton.bitmap = new Bitmap(buttonWidth, buttonHeight);
        this._registerButton.bitmap.fontSize = 20;
        this._registerButton.bitmap.drawText('注册', 0, 0, buttonWidth, buttonHeight, 'center');
        this._registerButton.x = x;
        this._registerButton.y = y;
        this._registerButton.setClickHandler(this.doRegister.bind(this));
        this.addChild(this._registerButton);
        
        // 返回按钮
        this._backButton = new Sprite_Button();
        this._backButton.bitmap = new Bitmap(buttonWidth, buttonHeight);
        this._backButton.bitmap.fontSize = 20;
        this._backButton.bitmap.drawText('返回', 0, 0, buttonWidth, buttonHeight, 'center');
        this._backButton.x = x + buttonWidth + 20;
        this._backButton.y = y;
        this._backButton.setClickHandler(this.popScene.bind(this));
        this.addChild(this._backButton);
    };
    
    Scene_Register.prototype.doRegister = async function() {
        const username = this._usernameWindow.text().trim();
        const password = this._passwordWindow.text().trim();
        const confirm = this._confirmWindow.text().trim();
        const email = this._emailWindow.text().trim();
        
        // 验证输入
        if (!username) {
            this.showStatus('请输入用户名', '#ff0000');
            return;
        }
        
        if (!password) {
            this.showStatus('请输入密码', '#ff0000');
            return;
        }
        
        if (password !== confirm) {
            this.showStatus('两次输入的密码不一致', '#ff0000');
            return;
        }
        
        this.showStatus('正在注册...', '#0000ff');
        
        try {
            await AuthClient.register(username, password, email);
            this.showStatus('注册成功！请登录', '#00ff00');
            
            // 延迟后返回登录界面
            setTimeout(() => {
                this.popScene();
            }, 1500);
        } catch (error) {
            this.showStatus(error.message || '注册失败', '#ff0000');
        }
    };
    
    Scene_Register.prototype.showStatus = function(text, color = '#000000') {
        this._statusWindow.clear();
        this._statusWindow.changeTextColor(color);
        this._statusWindow.drawText(text, 0, 0, this._statusWindow.width, this._statusWindow.lineHeight(), 'center');
    };
    
    // 输入文本窗口
    function Window_InputText(x, y, width, height, label, isPassword = false) {
        this.initialize(...arguments);
    }
    
    Window_InputText.prototype = Object.create(Window_Base.prototype);
    Window_InputText.prototype.constructor = Window_InputText;
    
    Window_InputText.prototype.initialize = function(x, y, width, height, label, isPassword = false) {
        Window_Base.prototype.initialize.call(this, x, y, width, height);
        this._label = label;
        this._isPassword = isPassword;
        this._text = '';
        this._cursorVisible = false;
        this._cursorCount = 0;
        this.createInputField();
        this.refresh();
    };
    
    Window_InputText.prototype.createInputField = function() {
        // 创建HTML输入元素
        this._input = document.createElement('input');
        this._input.type = this._isPassword ? 'password' : 'text';
        this._input.style.position = 'absolute';
        this._input.style.width = (this.width - 40) + 'px';
        this._input.style.height = (this.height - 20) + 'px';
        this._input.style.left = (this.x + 20) + 'px';
        this._input.style.top = (this.y + 10) + 'px';
        this._input.style.fontSize = '18px';
        this._input.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
        this._input.style.color = '#ffffff';
        this._input.style.border = '1px solid #cccccc';
        this._input.style.padding = '5px';
        this._input.style.zIndex = 100;
        
        // 输入事件监听
        const self = this;
        this._input.addEventListener('input', function() {
            self._text = this.value;
            self.refresh();
        });
        
        document.body.appendChild(this._input);
    };
    
    Window_InputText.prototype.setText = function(text) {
        this._text = text;
        this._input.value = text;
        this.refresh();
    };
    
    Window_InputText.prototype.text = function() {
        return this._text;
    };
    
    Window_InputText.prototype.refresh = function() {
        this.contents.clear();
        this.drawText(this._label + ':', 10, 0, this.width - 20, this.lineHeight());
    };
    
    Window_InputText.prototype.update = function() {
        Window_Base.prototype.update.call(this);
        this.updateCursor();
    };
    
    Window_InputText.prototype.updateCursor = function() {
        this._cursorCount++;
        if (this._cursorCount % 40 === 0) {
            this._cursorVisible = !this._cursorVisible;
            this.refresh();
        }
    };
    
    Window_InputText.prototype.destroy = function() {
        // 移除HTML元素
        if (this._input && this._input.parentNode) {
            this._input.parentNode.removeChild(this._input);
        }
        Window_Base.prototype.destroy.call(this);
    };
    
    // 按钮精灵
    function Sprite_Button() {
        this.initialize(...arguments);
    }
    
    Sprite_Button.prototype = Object.create(Sprite.prototype);
    Sprite_Button.prototype.constructor = Sprite_Button;
    
    Sprite_Button.prototype.initialize = function() {
        Sprite.prototype.initialize.call(this);
        this._clickHandler = null;
        this._hover = false;
        this.setupEventListeners();
    };
    
    Sprite_Button.prototype.setupEventListeners = function() {
        const self = this;
        
        this.addEventListener('pointerover', function() {
            self._hover = true;
            self.tint = [200, 200, 200, 255]; // 稍微变亮
        });
        
        this.addEventListener('pointerout', function() {
            self._hover = false;
            self.tint = [255, 255, 255, 255]; // 恢复原色
        });
        
        this.addEventListener('pointerdown', function() {
            self.tint = [150, 150, 150, 255]; // 按下效果
        });
        
        this.addEventListener('pointerup', function() {
            self.tint = self._hover ? [200, 200, 200, 255] : [255, 255, 255, 255];
            if (self._clickHandler) {
                self._clickHandler();
            }
        });
    };
    
    Sprite_Button.prototype.setClickHandler = function(handler) {
        this._clickHandler = handler;
    };
    
    // 修改标题场景，添加登录按钮
    const _Scene_Title_createCommandWindow = Scene_Title.prototype.createCommandWindow;
    Scene_Title.prototype.createCommandWindow = function() {
        _Scene_Title_createCommandWindow.call(this);
        
        // 如果未登录，添加登录按钮
        if (!AuthClient.isLoggedIn()) {
            this._commandWindow.setHandler('login', this.commandLogin.bind(this));
            
            // 插入登录命令
            const commands = this._commandWindow._list;
            commands.splice(1, 0, {
                name: '登录',
                symbol: 'login',
                enabled: true,
                ext: null
            });
        } else {
            // 如果已登录，添加用户信息和登出按钮
            this._commandWindow.setHandler('user', this.commandUserInfo.bind(this));
            this._commandWindow.setHandler('logout', this.commandLogout.bind(this));
            
            const user = AuthClient.getCurrentUser();
            const username = user ? user.username : '用户中心';
            
            // 插入用户命令
            const commands = this._commandWindow._list;
            commands.splice(1, 0, {
                name: username,
                symbol: 'user',
                enabled: true,
                ext: null
            }, {
                name: '登出',
                symbol: 'logout',
                enabled: true,
                ext: null
            });
        }
        
        this._commandWindow.refresh();
    };
    
    Scene_Title.prototype.commandLogin = function() {
        this._commandWindow.close();
        SceneManager.push(Scene_Login);
    };
    
    Scene_Title.prototype.commandUserInfo = function() {
        this._commandWindow.close();
        // 这里可以显示用户信息场景
        // SceneManager.push(Scene_UserInfo);
        this._commandWindow.open();
    };
    
    Scene_Title.prototype.commandLogout = function() {
        AuthClient.logout();
        this._commandWindow.close();
        // 重新创建命令窗口以更新按钮
        this.createCommandWindow();
        this._commandWindow.open();
    };
    
    // 自动登录检查
    const _Scene_Boot_start = Scene_Boot.prototype.start;
    Scene_Boot.prototype.start = async function() {
        // 先执行原始的start方法
        _Scene_Boot_start.call(this);
        
        // 检查是否需要自动登录
        if (AuthConfig.autoLogin && !AuthClient.isLoggedIn()) {
            try {
                // 尝试通过token获取用户信息
                await AuthClient.getUserInfo();
                console.log('自动登录成功');
            } catch (error) {
                console.log('自动登录失败:', error.message);
            }
        }
    };
})();
